<?php

/**
 * Post actions.
 *
 * @package    iceblog
 * @subpackage Post
 * @author     Jonathan Olger Nieto Lajo <ice_j7@hotmail.com>
 */
class PostActions extends ActionsProject
{
  public function executeShow(sfWebRequest $request)
  {
    Doctrine::getTable('Visit')->createAndSave($request->getPathInfoArray());
    
    $this->posts = Doctrine::getTable('Post')->findLastPosts(10);
    
    $this->post = Doctrine::getTable('Post')->findOneBySlug($request->getParameter('slug'));
    $this->redirectUnless($this->post, '@homepage');
    
    $this->getResponse()->setTitle($this->post->getTitle().' | Jonathan Nieto\'s Blog | jnieto.org');
    $this->getResponse()->addMeta('description', $this->post->getMetaDescription());
    $this->getResponse()->addMeta('keywords'   , $this->post->getMetaKeywords());
    
    $this->commentForm = new CommentForm();
    
    if ($request->isMethod('post'))
    {
      $params = $request->getParameter($this->commentForm->getName());
      $params = array_merge($params, $this->getCommentParams($request));
      $this->commentForm->bind($params);
      
      if ($this->commentForm->isValid())
      {
        $comment = $this->commentForm->save();
        $this->redirect('@post_show?slug='.$this->post->getSlug());
      }
    }
  }
  
  protected function getCommentParams(sfWebRequest $request)
  {
    $data   = $request->getPathInfoArray();
    
    $params = array();
    $params['post_id']   = $this->post->getId();
    $params['author_ip'] = $request->getRemoteAddress();
    $params['agent']     = $data['HTTP_USER_AGENT'];
    $params['approved']  = CommentTable::YES;
    
    return $params;
  }
}
